# -*- coding: utf-8 -*-
"""
高级筛选窗口功能实现
"""
import sqlite3
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QTableWidgetItem
from PyQt5.QtCore import Qt
from AdvancedFilter import Ui_MainWindow as AdvancedFilterUI
from menu_utils import window_manager

class AdvancedFilterWindow(QMainWindow):
    """高级筛选窗口类"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        # 创建UI实例
        self.ui = AdvancedFilterUI()
        # 设置UI
        self.ui.setupUi(self)
        # 连接信号与槽
        self._connect_signals()
    
    def _connect_signals(self):
        """连接按钮信号与槽函数"""
        self.ui.pushButton.clicked.connect(self._on_query)
        self.ui.pushButton_2.clicked.connect(self._on_reset)
    
    def _on_query(self):
        """查询按钮点击事件处理"""
        try:
            # 获取查询条件
            ip = self.ui.lineEdit.text().strip()
            start_time = self.ui.dateTimeEdit.dateTime().toSecsSinceEpoch()
            end_time = self.ui.dateTimeEdit_2.dateTime().toSecsSinceEpoch()
            log_keyword = self.ui.lineEdit_2.text().strip()
            prob_min = self.ui.doubleSpinBox.value() / 100.0  # 转换为0-1范围
            prob_max = self.ui.doubleSpinBox_2.value() / 100.0  # 转换为0-1范围
            location_keyword = self.ui.lineEdit_3.text().strip()
            
            # 构建查询SQL
            query_parts = []
            params = []
            
            # 添加时间范围条件
            query_parts.append("timestamp BETWEEN ? AND ?")
            params.extend([start_time, end_time])
            
            # 添加IP条件
            if ip:
                query_parts.append("ip LIKE ?")
                params.append(f"%{ip}%")
            
            # 添加日志关键字条件
            if log_keyword:
                query_parts.append("string LIKE ?")
                params.append(f"%{log_keyword}%")
            
            # 添加攻击概率范围条件
            query_parts.append("point >= ? AND point <= ?")
            params.extend([prob_min, prob_max])
            
            # 添加归属地关键字条件
            if location_keyword:
                query_parts.append("address LIKE ?")
                params.append(f"%{location_keyword}%")
            
            # 添加正则表达式判断结果条件
            regular_conditions = []
            if self.ui.checkBox.isChecked():
                # 考虑到字段可能是整数或字符串类型，使用更通用的条件
                regular_conditions.append("regular_result = 1 OR regular_result = '1'")
            if self.ui.checkBox_2.isChecked():
                regular_conditions.append("regular_result = 0 OR regular_result = '0'")
            
            # 如果有正则表达式判断结果条件，将它们用OR连接后作为一个整体条件
            if regular_conditions:
                query_parts.append(f"({' OR '.join(regular_conditions)})")
            
            # 构建完整SQL
            sql = f"""
                SELECT ip, address, string, point, regular_result, timestamp
                FROM nginx_logs 
                WHERE {' AND '.join(query_parts)} 
                ORDER BY timestamp DESC
            """
            
            print(f"执行查询: {sql}")
            print(f"参数: {params}")
            
            # 执行查询
            conn = sqlite3.connect('nginx_logs.db')
            cursor = conn.cursor()
            cursor.execute(sql, params)
            rows = cursor.fetchall()
            conn.close()
            
            print(f"查询结果: {len(rows)} 条记录")
            
            # 如果有结果，显示在聚合窗口中
            if rows:
                # 定义列信息
                columns = ['ip', 'address', 'url', 'point', 'regular_result', 'timestamp']
                column_headers = ['IP', '归属', 'URL', '攻击概率(%)', '正则结果', '时间']
                
                # 预处理数据，确保regular_result正确显示
                processed_rows = []
                for row in rows:
                    # 检查是否有regular_result字段且位置正确
                    if len(row) >= 5:
                        # 复制原行数据
                        processed_row = list(row)
                        # 处理regular_result字段
                        if processed_row[4] == 1 or processed_row[4] == '1':
                            processed_row[4] = '攻击'
                        elif processed_row[4] == 0 or processed_row[4] == '0':
                            processed_row[4] = '正常'
                        else:
                            processed_row[4] = '未判断'
                        processed_rows.append(processed_row)
                    else:
                        processed_rows.append(row)
                rows = processed_rows
                
                # 使用窗口管理器显示结果
                window_id = "advanced_filter_result"
                title = f"高级筛选结果 ({len(rows)} 条记录)"
                
                result_window = window_manager.update_window(
                    window_id, title, rows, columns, column_headers
                )
                
                # 如果成功创建窗口，关闭筛选窗口
                if result_window:
                    self.close()
            else:
                # 没有找到结果
                QMessageBox.information(self, "查询结果", "没有找到符合条件的记录")
                
        except Exception as e:
            print(f"查询时出错: {e}")
            import traceback
            traceback.print_exc()
            QMessageBox.critical(self, "错误", f"查询时出错: {str(e)}")
    
    def _on_reset(self):
        """重置按钮点击事件处理"""
        self.ui.lineEdit.clear()
        self.ui.lineEdit_2.clear()
        self.ui.lineEdit_3.clear()
        self.ui.doubleSpinBox.setValue(0.0)
        self.ui.doubleSpinBox_2.setValue(100.0)
        self.ui.checkBox.setChecked(False)
        self.ui.checkBox_2.setChecked(False)
        
        # 重置时间范围（当前时间和未来3个月）
        from PyQt5.QtCore import QDateTime, QDate, QTime
        current_time = QDateTime.currentDateTime()
        self.ui.dateTimeEdit.setDateTime(current_time.addMonths(-10))  # 10个月前
        self.ui.dateTimeEdit_2.setDateTime(current_time.addMonths(1))  # 1个月后


def show_advanced_filter(parent=None):
    """显示高级筛选窗口的函数"""
    try:
        # 创建并显示高级筛选窗口
        advanced_window = AdvancedFilterWindow(parent)
        advanced_window.show()
        advanced_window.raise_()
        return advanced_window
    except Exception as e:
        print(f"显示高级筛选窗口时出错: {e}")
        import traceback
        traceback.print_exc()
        return None